﻿using Microsoft.Practices.Prism.StoreApps;
using System;
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace EasySchedule.Controls
{
    public sealed partial class AuthorizationView : UserControl
    {
        public static readonly DependencyProperty AuthorizationUrlProperty =
            DependencyProperty.Register("AuthorizationUrl", typeof(Uri),
            typeof(AuthorizationView), new PropertyMetadata(null));

        public static readonly DependencyProperty LogInCommandProperty =
            DependencyProperty.Register("LogInCommand", typeof(ICommand), typeof(AuthorizationView),
            new PropertyMetadata(null));

        private Action<Uri> callback;

        public AuthorizationView()
        {
            this.InitializeComponent();
            this.Loaded += AuthorizationView_Loaded;
        }

        public Uri AuthorizationUrl
        {
            get { return (Uri)GetValue(AuthorizationUrlProperty); }
            set { SetValue(AuthorizationUrlProperty, value); }
        }

        public ICommand LogInCommand
        {
            get { return (ICommand)GetValue(LogInCommandProperty); }
            set { SetValue(LogInCommandProperty, value); }
        }

        private void AuthorizationView_Loaded(object sender, RoutedEventArgs e)
        {
            this.LogInCommand = new DelegateCommand<Action<Uri>>(ExecuteLogIn, CanExecuteLogIn);
        }

        private void AuthorizeWebView_LoadCompleted(object sender, NavigationEventArgs e)
        {
            if (e.Uri.Host != this.AuthorizationUrl.Host)
            {
                this.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.callback(e.Uri);
            }
        }

        private bool CanExecuteLogIn(Action<Uri> callback)
        {
            if (this.Visibility == Windows.UI.Xaml.Visibility.Visible) return false;
            return true;
        }

        private void ExecuteLogIn(Action<Uri> callback)
        {
            this.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.callback = callback;
            this.AuthorizeWebView.LoadCompleted += AuthorizeWebView_LoadCompleted;
            this.AuthorizeWebView.Navigate(this.AuthorizationUrl);
        }
    }
}